#include "yonghu.h"
#include "ui_yonghu.h"
#include <QIcon>
#include <QToolButton>
#include <QMessageBox>
#include <QDebug>
yonghu::yonghu(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::yonghu)
{
    ui->setupUi(this);
    //设置图标
    this->setWindowIcon(QIcon(":/images/qq.png"));
    //设置名称
    this->setWindowTitle("登录");

    //设置默认端口和IP
    ui->port->setText("8899");
    ui->ip->setText("127.0.0.1");

    ui->disconnect->setDisabled(true);

    m_tcp=new QTcpSocket;

    connect(m_tcp,&QTcpSocket::connected,this,[=](){
        QMessageBox::information(this,"连接","已成功连接服务器！");

        ui->connect->setDisabled(true);
        ui->disconnect->setEnabled(true);
    });

    connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
        QString data=m_tcp->readAll();
        qDebug()<< "data=" << data;
        if(data.startsWith("/ok")){
            Widget* w = new Widget(nullptr,ui->userName->text(),m_tcp);
            // 登录成功后，断开所有信号槽连接
            disconnect(m_tcp, nullptr, this, nullptr);  // 断开 m_tcp 与当前对象的所有连接
            m_tcp->setParent(w);
            this->hide();
            w->show();
        }
        else{
            QMessageBox::warning(this,"警告","用户名已存在或用户名不能为空!!!");
        }
    });

    connect(m_tcp,&QTcpSocket::disconnected,this,[=](){
        m_tcp->close();
        QMessageBox::information(this,"连接","已断开连接...");
        ui->connect->setDisabled(false);
        ui->disconnect->setEnabled(false);
    });



}

yonghu::~yonghu()
{
    delete ui;
}

//连接服务器
void yonghu::on_connect_clicked()
{
    quint16 port = ui->port->text().toUShort();
    QString ip = ui->ip->text();
    m_tcp->connectToHost(ip,port);
}

//断开连接
void yonghu::on_disconnect_clicked()
{
    m_tcp->close();
    QMessageBox::information(this,"连接","已断开连接...");
    ui->connect->setDisabled(false);
    ui->disconnect->setEnabled(false);
}


//创建用户
void yonghu::on_createUser_clicked()
{
    if(!m_tcp||m_tcp->state() != QAbstractSocket::ConnectedState){
        QMessageBox::warning(this,"警告","请先连接服务器,再创建用户！！！");
        return;
    }
    QString name = "/login:" + ui->userName->text()+"\x1F";
    m_tcp->write(name.toUtf8());
}
